package com.config;

import com.entity.Students;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.jboss.C3P0PooledDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

@Configuration
@ComponentScan(basePackages = "com") //扫描带注解的包
@EnableAspectJAutoProxy  //开启aspectJ注解

public class MySpringConfiguration {

    @Bean("s1")
    public Students initStudents() {
        return new Students("S0001", "张三丰", "男", "太极拳");
    }


    @Bean("studentList")
    public List<Students> initStudentList() {
        List<Students> studentsList = new ArrayList<Students>();
        studentsList.add(new Students("S0002", "刘备", "男", "软件工程"));
        studentsList.add(new Students("S0003", "关羽", "男", "软件工程"));
        studentsList.add(new Students("S0004", "张飞", "男", "软件工程"));
        return studentsList;
    }

    //自己去初始化一个C3p0的数据源
    @Bean("jdbcTemplate")
    public JdbcTemplate initC3p0DataSource() {
        ComboPooledDataSource dataSource = null;
        Properties properties = null;
        JdbcTemplate jdbcTemplate = null;
        try {
            dataSource = new ComboPooledDataSource();
            properties = new Properties();
            properties.load(MySpringConfiguration.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            dataSource.setUser(properties.getProperty("jdbc.user"));
            dataSource.setPassword(properties.getProperty("jdbc.password"));
            dataSource.setDriverClass(properties.getProperty("jdbc.driverClass"));
            dataSource.setJdbcUrl(properties.getProperty("jdbc.jdbcUrl"));
            dataSource.setInitialPoolSize(Integer.parseInt(properties.getProperty("initPoolSize")));
            dataSource.setMaxPoolSize(Integer.parseInt(properties.getProperty("maxPoolSize")));
            jdbcTemplate = new JdbcTemplate();
            jdbcTemplate.setDataSource(dataSource);
            return jdbcTemplate;

        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
}
